/**********************************************************************************************
* File: s3base_ui2.js
* Name: Sal Fuentes Jr.
* Date: 09/06/2008
* Info: javascript file that contains ExtJS UI definitions for s3base
**********************************************************************************************/

var gbCurrentlySelectedBucket = null;
var getBucketsUrl = '/getBuckets';
if ( s3FoxView == true )
  getBucketsUrl += '?view=s3fox';

Ext.onReady(function(){
    var credentialsFormPanel = new Ext.FormPanel({
        frame: true,
        title: 'S3 Credentials',
        id: 'credentials-form',
        height: 250,
        defaults: {width: 175},
        defaultType: 'textfield',
        labelAlign: 'top',
        buttons: [{text: 'Load Buckets', handler: function() { Ext.getCmp('ctr-tab-panel').setActiveTab('buckettree'); } }],
        items: [{
                fieldLabel: 'ACCESS_KEY_ID',
                id: 'access-key',
                value: '043ENN4RX5HCXCHQNS82',
                allowBlank: false
            },{
                fieldLabel: 'SECRET_ACCESS_KEY',
                id: 'secret-key',
                value: '8IzTK50MtGvkrsK9G48fo+CugXtJC+yPUZGdjImk',
                inputType: 'password',
                allowBlank: false
            }
        ]      
    });
         
    var bucketTree = new Ext.tree.TreePanel({
        id: 'buckettree',
        frame: true,
        title: 'Buckets',
        height: 250,
        useArrows:true,
        autoScroll:true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        // auto create TreeLoader
        dataUrl: getBucketsUrl,
        rootVisible: false,
        root: {
            nodeType: 'async',
            text: 'Buckets',
            draggable: false,
            id: 'root'
        }
    });
    // Create event handler for selecting bucket from tree
    bucketTree.on("click", function(node, e) {
      if(IsCredentialsFormFilledOut() == true)
        reloadKeysGrid(node);        
    });
    bucketTree.on("show", function(thisTreePanel) {
      if(IsCredentialsFormFilledOut() == true) {      
        var treeLoader = thisTreePanel.getLoader();
        treeLoader.baseParams.awsAccessKeyId = Ext.getCmp('access-key').getValue();
        treeLoader.baseParams.awsSecretKey = Ext.getCmp('secret-key').getValue();
      }
      else
        Ext.getCmp('ctr-tab-panel').setActiveTab('credentials-form');
    }, this);
    
    var controlTabPanel = new Ext.TabPanel({
      id: 'ctr-tab-panel',
      activeTab: 0,
      height: 300,
      items: [credentialsFormPanel, bucketTree]
    });
    var controlPanel = new Ext.Panel({
      baseCls: 'x-box',
      frame: true,
      renderTo: 'control-panel',
      items: controlTabPanel
    });
    
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    
    var s3keysJsonStore = new Ext.data.JsonStore({
        url: '/getKeys',
        baseParams: {
            awsAccessKeyId: Ext.getCmp('access-key').getValue(),
            awsSecretKey: Ext.getCmp('secret-key').getValue()
        },
        root: 'keys',
        fields: ['key', {name:'fileSize', type: 'int'}, {name:'lastMod', type:'date'}]
    });      
    
    // create the Grid
    var chkboxSM = new Ext.grid.CheckboxSelectionModel();
    var keysGrid = new Ext.grid.GridPanel({
        id: 'keys-grid',
        store: s3keysJsonStore,
        colModel: new Ext.grid.ColumnModel([
            chkboxSM,
            {id:'key', header: "Key Name", width: 300, sortable: true, dataIndex: 'key'},
            {header: "File Size(KB)", width: 75, sortable: true, dataIndex: 'fileSize'},
            {header: "Last Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastMod'}
        ]),
        selModel: chkboxSM,
         // inline toolbars
        tbar:[{
            text:'Add S3 Object',
            id: 'adds3objbtn',
            tooltip:'Add a new object',
            iconCls:'add',
            handler: openDialog
        }, '-', {
            text:'Remove S3 Object',
            tooltip:'Remove the selected object',
            iconCls:'remove',
            handler: removeS3Obj          
        },'-',{
            text:'Options...',
            tooltip:'Other Options',
            iconCls:'option'
        }],
        bbar: new Ext.StatusBar({
            defaultText: 'Done',
            id: 'right-statusbar',
            statusAlign: 'right', // the magic config
            items: [{
                text: 'Cmd'
            }, '-', 'S3 Obj Data', ' ', ' ']
        }),          
        frame: true,
        baseCls: 'x-box',
        iconCls: 'icon-grid',
        stripeRows: true,
        height: 350,
        width: 600
    });
    
    keysGrid.render('keys-grid');
    keysGrid.getSelectionModel().selectFirstRow();
    
    var msg = function(title, msg){
        Ext.Msg.show({
            title: title, 
            msg: msg,
            minWidth: 200,
            modal: true,
            icon: Ext.Msg.INFO,
            buttons: Ext.Msg.OK
        });
    };      
    
    var uploadForm = new Ext.FormPanel({
      id: 'upload-form',
      fileUpload: true,
      width: 500,
      frame: true,
      autoHeight: true,
      bodyStyle: 'padding: 10px 10px 0 10px;',
      labelWidth: 50,
      defaults: {
        anchor: '95%',
        allowBlank: false,
        msgTarget: 'side'
      },
      items: [{
        xtype: 'fileuploadfield',
        id: 'form-file',
        emptyText: 'Select a file to upload',
        fieldLabel: 'File',
        name: 'fileData',
        buttonCfg: {
          text: '',
          iconCls: 'upload-icon'
        }
      }],
      buttons: [{
          text: 'Upload',
          handler: function(){ uploadFile(); }
        },{
          text: 'Reset',
          handler: function(){ uploadForm.getForm().reset(); }
      }]
  });
        
function uploadFile() {
  var treeSelModel = Ext.getCmp('buckettree').getSelectionModel();
  var fileName = Ext.getCmp('form-file').getValue();
  var uploadForm = Ext.getCmp('upload-form');
  if(gbCurrentlySelectedBucket != null && fileName != null) {
    var selectedBucketNode = treeSelModel.getSelectedNode();
    if(uploadForm.getForm().isValid()) {
      if(IsCredentialsFormFilledOut() == true) {
        uploadForm.getForm().submit({
            url: '/putS3Obj',
            params: {
              awsAccessKeyId: Ext.getCmp('access-key').getValue(),
              awsSecretKey: Ext.getCmp('secret-key').getValue(),             
              bucketName: selectedBucketNode.id,
              keyName: fileName 
            },
            waitMsg: 'Uploading your file to S3...',
            success: function(basicForm, o){
                reloadKeysGrid(gbCurrentlySelectedBucket);
                uploadWindow.hide();
                basicForm.reset();
                msg('Success', 'Processed file "'+o.result.filename+'" on the server');
            }
        });
      }
    }
  }
  else {
    Ext.Msg.alert('Error', 'First select a bucket and file');
  }
}              
    
    // Create event handler for double clicking a row in the grid
    keysGrid.on("rowdblclick", function(thisgrid, rowIndex, e) {
      if(IsCredentialsFormFilledOut() == true) {
        var keySelected = keysGrid.getStore().getAt(rowIndex).get('key');
        var bucketSelected = bucketTree.getSelectionModel().getSelectedNode().id
        Ext.Ajax.request({
          url: '/getS3ObjUrl',
          success: function(response) { 
            var s3ObjUrl = eval( "(" + response.responseText + ")" ).url;
            window.open(s3ObjUrl,keySelected,'width=600,height=400');
          },
          params: { 
            awsAccessKeyId: Ext.getCmp('access-key').getValue(),
            awsSecretKey: Ext.getCmp('secret-key').getValue(),
            bucketName: bucketSelected,
            keyName: keySelected
          }
        });
      }
    });       
      
});
